import axios from "axios";
import { MessageBox, Message } from "element-ui";
import store from "@/store";
import { getToken, downLoad } from "@/utils/auth";
import router from "../router";
import qs from "qs";
// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  // baseURL: 'http://127.0.0.1:8088/',
  // baseURL:
  //   location.hostname !== "localhost" ? "http://127.0.0.1:8088/" : "/api", // url = base url + request url
  // baseURL:
  //   location.hostname !== "localhost"
  //     ? "http://scs-system.natapp1.cc/"
  //     : "/api", // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 50030, // request timeout
  headers: {
    // 'Content-Type': 'application/x-www-form-urlencoded'
    // 'Content-Type': 'application/x-www-form-urlencoded'
  },
});

// request interceptor
service.interceptors.request.use(
  (config) => {
    // console.log(config, process.env)
    // config.data = qs.stringify(config.data)
    // do something before request is sent
    // if (store.getters.token) {
    // let each request carry token
    // ['X-Token'] is a custom headers key
    // please modify it according to the actual situation
    // console.log(store.state.user.token);

    // config.headers["X-Token"] = store.state.user.token;
    const arr = [
      "/scene/sceneManager/add",
      "/scene/sceneManager/edit",
      "/system/menu/edit",
      "/system/role/add",
      "/system/role/edit",
      "/system/dict/edit",
      "/scene/sceneChildNodeManager/edit",
    ];
    if (arr.includes(config.url)) {
      config.headers["Content-Type"] = "application/json";
    } else {
      // console.log(2)
      config.data = qs.stringify(config.data);
      config.headers["Content-Type"] = "application/x-www-form-urlencoded";
    }
    // }
    return config;
  },
  (error) => {
    // do something with request error
    console.log(error); // for debug
    return Promise.reject(error);
  }
);

// response interceptor
service.interceptors.response.use(
  (response) => {
    const res = response.data;
    // console.log(res.code)
    // if the custom code is not 20000, it is judged as an error.
    if (res.code && res.code !== 200) {
      if (res.msg) {
        Message({
          message: res.msg || "操作失败",
          type: "error",
          duration: 5 * 1000,
        });
      }

      // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
      if (res.code == "1" || res.code == "401") {
        // to re-login
        router.push("/login");
      }
      return Promise.reject(new Error(res.message || "Error"));
    } else if (
      response.config.url.indexOf("downLoadFile") > -1 ||
      response.config.url.indexOf("downLoadTmplFile") > -1
    ) {
      const Url = response.headers["content-disposition"];
      const fileName = Url?.split(";")[1].split("filename=")[1] || "文件";
      const blob = new Blob([res]);
      const blobUrl = window.URL.createObjectURL(blob);
      const a = document.createElement("a");
      a.download = fileName;
      a.style.display = "none";
      a.href = blobUrl;
      a.click();
      document.body.removeChild(a);
    } else {
      return res;
    }
  },
  (error) => {
    console.log("err" + error); // for debug
    Message({
      message: error.message,
      type: "error",
      duration: 5 * 1000,
    });
    return Promise.reject(error);
  }
);

export default service;
